<template>
  <div class="app-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" class="mb-20">
      <el-breadcrumb-item :to="{ path: '/system/banner' }">Banner管理</el-breadcrumb-item>
      <el-breadcrumb-item>{{ title }}</el-breadcrumb-item>
    </el-breadcrumb>
    
    <el-card v-loading="loading">
      <div slot="header">
        <span>{{ title }}</span>
      </div>
      
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="Banner标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入Banner标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序权重" prop="sortOrder">
              <el-input-number v-model="form.sortOrder" :min="0" :max="999" controls-position="right" placeholder="请输入排序权重" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="跳转类型" prop="linkType">
              <el-select v-model="form.linkType" placeholder="请选择跳转类型">
                <el-option label="Web页" :value="1"></el-option>
                <el-option label="原生页面" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="展示类型" prop="bannerType">
              <el-select v-model="form.bannerType" placeholder="请选择展示类型">
                <el-option label="图片" :value="1"></el-option>
                <el-option label="视频" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="跳转链接" prop="linkUrl" v-if="form.linkType !== 2">
              <el-input v-model="form.linkUrl" placeholder="请输入跳转链接" />
            </el-form-item>
            <el-form-item label="原生页面路径" prop="linkUrl" v-else>
              <el-input v-model="form.linkUrl" placeholder="请输入原生页面路径" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="投放页面" prop="bannerPage">
              <el-input v-model="form.bannerPage" placeholder="请输入投放页面路径" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态">
                <el-option label="停用" :value="0"></el-option>
                <el-option label="正常" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="Banner描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入Banner描述" />
        </el-form-item>
        
        <!-- 图片类型 -->
        <el-form-item label="Banner图片" prop="imageUrl" v-if="form.bannerType === 1">
          <EditImage
            v-model="form.imageUrl"
            :auto-append-url="true"
            :image-url-prefix="BASE_FILE_URL"
            :cropper-config="{
              autoCrop: true,
              autoCropWidth: 750,
              autoCropHeight: 400,
              fixedBox: false,
              outputType: 'png'
            }"
            :dialog-width="'800px'"
            :cropper-height="450"
            upload-tip="支持 JPG、PNG 格式，建议尺寸 750x400，文件大小不超过 5MB"
            placeholder-text="请上传Banner图片，建议尺寸 750x400 像素"
            cropper-title="Banner图片裁剪"
            :max-file-size="5"
            @image-cropped="onImageCropped"
            @image-removed="onImageRemoved"
          />
        </el-form-item>
        
        <!-- 视频类型 -->
        <el-form-item label="Banner视频" prop="imageUrl" v-if="form.bannerType === 2">
          <div class="video-upload-container">
            <div class="video-preview" v-if="form.imageUrl">
              <video 
                :src="getFullImageUrl(form.imageUrl)" 
                style="width: 200px; height: 120px;"
                controls>
              </video>
              <div class="video-actions">
                <el-button size="mini" type="primary" @click="editVideo">编辑视频</el-button>
                <el-button size="mini" type="danger" @click="removeVideo">删除</el-button>
              </div>
            </div>
            <el-upload 
              v-else
              action="#" 
              :http-request="uploadVideo" 
              :show-file-list="false" 
              :before-upload="beforeUploadVideo"
              accept="video/*">
              <el-button size="small">
                选择视频
                <i class="el-icon-upload el-icon--right"></i>
              </el-button>
            </el-upload>
            <div class="upload-tip">支持 MP4、AVI、MOV 格式，文件大小不超过 50MB</div>
          </div>
        </el-form-item>
        
        <!-- VR类型 -->
        <el-form-item label="VR内容" prop="imageUrl" v-if="form.bannerType === 3">
          <el-input v-model="form.imageUrl" placeholder="请输入VR内容链接" />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getBanner, addBanner, updateBanner, uploadBannerFile } from "@/api/system/banner"
import { VueCropper } from "vue-cropper"
import { debounce } from '@/utils'
import EditImage from '@/components/EditImage/EditImage.vue'
import { BASE_FILE_URL, BASE_API } from '@/utils/constants'

export default {
  name: "BannerForm",
  components: { VueCropper, EditImage },
  data() {
    return {
      // 文件服务器基础URL
      BASE_FILE_URL: BASE_FILE_URL,
      BASE_API: BASE_API, // 添加BASE_API到data中
      // 弹出层标题
      title: "",
      // 表单参数
      form: {
        bannerId: null,
        title: null,
        description: null,
        imageUrl: null,
        linkUrl: null,
        linkType: 1,
        bannerType: 1,
        sort: 0,
        status: 1,
        bannerPage: null,
        createTime: null,
        updateTime: null
      },
      // 表单校验
      rules: {
        imageUrl: [
          { 
            required: true, 
            validator: (rule, value, callback) => {
              if (this.form.bannerType === 1 && !value) {
                callback(new Error('Banner图片不能为空'))
              } else if (this.form.bannerType === 2 && !value) {
                callback(new Error('Banner视频不能为空'))
              } else if (this.form.bannerType === 3 && !value) {
                callback(new Error('VR内容链接不能为空'))
              } else {
                callback()
              }
            }, 
            trigger: "blur" 
          }
        ],
        // linkUrl: [
        //   { 
        //     required: true, 
        //     validator: (rule, value, callback) => {
        //       if (this.form.linkType !== 2 && !value) {
        //         callback(new Error('跳转链接不能为空'))
        //       } else if (this.form.linkType === 2 && !value) {
        //         callback(new Error('原生页面路径不能为空'))
        //       } else {
        //         callback()
        //       }
        //     }, 
        //     trigger: "blur" 
        //   }
        // ],
        linkType: [
          { required: true, message: "跳转类型不能为空", trigger: "change" }
        ],
        bannerType: [
          { required: true, message: "展示类型不能为空", trigger: "change" }
        ],
        sort: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      },
      // 图片裁剪相关
      croppedImageBlob: null,
      // 加载状态
      loading: false
    }
  },
  created() {
    this.initForm()
  },
  watch: {
    'form.bannerType'(newVal, oldVal) {
      // 当展示类型改变时，清空资源URL
      if (newVal !== oldVal) {
        this.form.imageUrl = null
        this.croppedImageBlob = null
      }
    },
    'form.linkType'(newVal, oldVal) {
      // 当跳转类型改变时，清空链接URL
      if (newVal !== oldVal) {
        this.form.linkUrl = null
      }
    }
  },
  methods: {
    /** 初始化表单 */
    initForm() {
      const { bannerId } = this.$route.query
      if (bannerId) {
        // 编辑模式
        this.title = "修改Banner"
        this.getBannerData(bannerId)
      } else {
        // 新增模式
        this.title = "添加Banner"
        this.reset()
      }
    },
    /** 获取Banner数据 */
    getBannerData(id) {
      this.loading = true
      getBanner(id).then(response => {
        this.form = response.data
        this.loading = false
      }).catch(() => {
        this.loading = false
        this.$message.error('获取Banner数据失败')
      })
    },
    /** 拼接服务器图片地址 */
    getFullImageUrl(imageUrl) {
      if (!imageUrl) return '';
      // 如果已经是http/https/base64开头，直接返回
      if (/^(http|https):\/\//.test(imageUrl) || imageUrl.startsWith('data:image/')) {
        return imageUrl;
      }
      // 兼容斜杠
      if (imageUrl.startsWith('/')) {
        return this.BASE_API + imageUrl;
      }
      // 默认拼接文件服务器路径
      return this.BASE_FILE_URL + imageUrl;
    },
    // 表单重置
    reset() {
      this.form = {
        bannerId: null,
        title: null,
        description: null,
        imageUrl: null,
        linkUrl: null,
        linkType: 1,
        bannerType: 1,
        sort: 0,
        status: 1,
        bannerPage: null,
        createTime: null,
        updateTime: null
      }
      this.croppedImageBlob = null // 新增：重置裁剪图片
      this.resetForm("form")
    },
    /** 返回列表 */
    goBack() {
      this.$router.back()
    },
    /** 取消按钮 */
    cancel() {
      this.$modal.confirm('确定要取消编辑吗？未保存的内容将丢失。').then(() => {
        this.goBack()
      }).catch(() => {})
    },
    /** 提交按钮 */
    async submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          this.loading = true
          // 处理图片上传（新增或修改时）
          if (this.croppedImageBlob) {
            // 有裁剪后的图片blob，先上传图片
            try {
              const formData = new FormData()
              formData.append('file', this.croppedImageBlob, 'banner.png')
              formData.append('type', 4) // Banner图片
              const res = await uploadBannerFile(formData)
              if (res && res.code === 200 && res.fileName) {
                this.form.imageUrl = res.fileName || res.url // 兼容返回格式
              } else {
                this.$modal.msgError("图片上传失败")
                this.loading = false
                return
              }
            } catch (e) {
              this.$modal.msgError("图片上传失败")
              this.loading = false
              return
            }
          }
          
          if (this.form.bannerId != null) {
            updateBanner(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.loading = false
              this.goBack()
            }).catch(() => {
              this.loading = false
            })
          } else {
            addBanner(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.loading = false
              this.goBack()
            }).catch(() => {
              this.loading = false
            })
          }
        }
      })
    },
    // EditImage组件回调方法
    onImageCropped(blob, base64Url) {
      this.croppedImageBlob = blob
      console.log('图片裁剪完成:', blob, base64Url)
    },
    onImageRemoved() {
      this.croppedImageBlob = null
      console.log('图片已删除')
    },
    
    // 视频上传相关方法
    beforeUploadVideo(file) {
      const isVideo = file.type.startsWith('video/')
      const isLt50M = file.size / 1024 / 1024 < 50
      
      if (!isVideo) {
        this.$message.error('只能上传视频文件!')
        return false
      }
      if (!isLt50M) {
        this.$message.error('视频文件大小不能超过 50MB!')
        return false
      }
      return true
    },
    
    async uploadVideo(options) {
      try {
        const formData = new FormData()
        formData.append('file', options.file)
                    formData.append('type', 5) // 视频文件
        
        const res = await uploadBannerFile(formData)
        if (res && res.code === 200 && res.fileName) {
          this.form.imageUrl = res.fileName || res.url
          this.$message.success('视频上传成功')
        } else {
          this.$message.error('视频上传失败')
        }
      } catch (error) {
        console.error('视频上传错误:', error)
        this.$message.error('视频上传失败')
      }
    },
    
    editVideo() {
      this.form.imageUrl = null
    },
    
    removeVideo() {
      this.$modal.confirm('确定要删除这个视频吗？').then(() => {
        this.form.imageUrl = null
        this.$message.success('视频已删除')
      }).catch(() => {})
    }
  }
}
</script>

<style scoped lang="scss">
.video-upload-container {
  .video-preview {
    display: flex;
    align-items: center;
    gap: 10px;
    
    .video-actions {
      display: flex;
      flex-direction: column;
      gap: 5px;
    }
  }
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.4;
}

// 表单验证错误时的样式
.el-form-item.is-error .upload-tip {
  color: #f56c6c;
}

// 面包屑导航样式
.mb-20 {
  margin-bottom: 20px;
}
</style> 